.NET Core로 Terraform Cloud 관리

9528 단어 terraformdotnetcore
오늘은 Terraform Cloud 라이브러리를 사용하여 .NET Core로 Tfe.NetClient을 관리하는 방법을 보여 드리겠습니다.

아이디어는 다음을 수행하는 간단한 콘솔 응용 프로그램을 만드는 것입니다.
  • GitHub를 VCS Provider 으로 추가합니다.
  • Terraform 파일이 있는 GitHub 리포지토리에 연결된 Workspace을 만듭니다.
  • 작업 공간에 variable을 만듭니다.
  • Terraform 파일을 기반으로 실행(계획) 생성
  • 실행을 적용합니다.

  • Tfe.NetClient is still in alpha and not every Terraform Cloud API or feature is present. Please feel free to submit any issues, bugs or pull requests.



    전제 조건


  • A Terraform Cloud 계정 (Free Organization을 만들 수 있습니다)
  • A Terraform Cloud 조직
  • A Terraform Cloud Organization Token
  • A Terraform Cloud Team Token
  • 다음 권한이 있는 AGitHub Personal Access Token:
  • repo: repo:status 액세스 커밋 상태
  • repo: repo_deployment 배포 상태 액세스
  • repo: public_repo 공개 리포지토리에 액세스
  • repo: repo:invite Access 저장소 초대
  • repo: security_events 보안 이벤트 읽기 및 쓰기
  • 워크플로

  • 실행하려는 Terraform 스크립트가 있는 GitHub 저장소.

  • 1. 새 프로젝트를 위한 폴더 만들기




    명령 프롬프트를 열고 실행:

    mkdir TerraformCloud
    


    2. 프로젝트 생성





    cd TerraformCloud
    dotnet new console
    


    3. Tfe.NetClient에 대한 참조 추가





    dotnet add package Tfe.NetClient -v 0.1.0
    dotnet restore
    


    4. Program.cs의 내용을 다음 코드로 바꿉니다.





    namespace TerraformCloud
    {
        using System;
        using System.Net.Http;
        using System.Threading.Tasks;
        using Tfe.NetClient;
        using Tfe.NetClient.OAuthClients;
        using Tfe.NetClient.Runs;
        using Tfe.NetClient.Workspaces;
        using Tfe.NetClient.WorkspaceVariables;
    
        class Program
        {
            static async Task Main(string[] args)
            {
                // The values of this variables are hardcoded here just for simplicity and should be retrieved from configuration.
                var organizationName = "<organizationName>";
                var organizationToken = "<organizationToken>";
                var teamToken = "<teamToken>";
                var gitHubToken = "<GitHub Personal Access Token>";
                var gitHubRepo = "<github user or organization name>/<repo name>"; // i.e. cmendible/terraform-hello-world
    
                // Create an HttpClient
                var httpClient = new HttpClient();
    
                // Create the Configiration used by the TFE client.
                // For management tasks you'll need to connect to Terraform Cloud using an Organization Token.
                var config = new TfeConfig(organizationToken, httpClient);
    
                // Create the TFE client.
                var client = new TfeClient(config);
    
                // Connect Terraform Cloud and GitHub adding GitHub as a VCS Provider.
                var oauthClientsRequest = new OAuthClientsRequest();
                oauthClientsRequest.Data.Attributes.ServiceProvider = "github";
                oauthClientsRequest.Data.Attributes.HttpUrl = new Uri("https://github.com");
                oauthClientsRequest.Data.Attributes.ApiUrl = new Uri("https://api.github.com");
                oauthClientsRequest.Data.Attributes.OAuthTokenString = gitHubToken; // Use the GitHub Personal Access Token
                var oauthResult = await client.OAuthClient.CreateAsync(organizationName, oauthClientsRequest);
    
                // Get the OAuthToken.
                var oauthTokenId = oauthResult.Data.Relationships.OAuthTokens.Data[0].Id;
    
                // Create a Workspace connected to a GitHub repo.
                var workspacesRequest = new WorkspacesRequest();
                workspacesRequest.Data.Attributes.Name = "my-workspace";
                workspacesRequest.Data.Attributes.VcsRepo = new RequestVcsRepo();
                workspacesRequest.Data.Attributes.VcsRepo.Identifier = gitHubRepo; // Use the GitHub Repo
                workspacesRequest.Data.Attributes.VcsRepo.OauthTokenId = oauthTokenId;
                workspacesRequest.Data.Attributes.VcsRepo.Branch = "";
                workspacesRequest.Data.Attributes.VcsRepo.DefaultBranch = true;
                var workspaceResult = await client.Workspace.CreateAsync(organizationName, workspacesRequest);
    
                // Get the Workspace Id so we can add variales or request a plan or apply.
                var workspaceId = workspaceResult.Data.Id;
    
                // Create a variable in the workspace.
                // You can make the values invible setting the Sensitive attribute to true.
                // If you want to se an environement variable change the Category attribute to "env".
                // You'll have to create as any variables your script needs.
                var workspaceVariablesRequest = new WorkspaceVariablesRequest();
                workspaceVariablesRequest.Data.Attributes.Key = "variable_1";
                workspaceVariablesRequest.Data.Attributes.Value = "variable_1_value";
                workspaceVariablesRequest.Data.Attributes.Description = "variable_1 description";
                workspaceVariablesRequest.Data.Attributes.Category = "terraform";
                workspaceVariablesRequest.Data.Attributes.Hcl = false;
                workspaceVariablesRequest.Data.Attributes.Sensitive = false;
                var variableResult = await client.WorkspaceVariable.CreateAsync(workspaceId, workspaceVariablesRequest);
    
                // Get the workspace by name.
                var workspace = client.Workspace.ShowAsync(organizationName, "my-workspace");
    
                // To create Runs and Apply thme you need to use a Team Token.
                // So create a new TfeClient.
                var runsClient = new TfeClient(new TfeConfig(teamToken, new HttpClient()));
    
                // Create the Run.
                // This is th equivalent to running: terraform plan. 
                var runsRequest = new RunsRequest();
                runsRequest.Data.Attributes.IsDestroy = false;
                runsRequest.Data.Attributes.Message = "Triggered by .NET Core";
                runsRequest.Data.Relationships.Workspace.Data.Type = "workspaces";
                runsRequest.Data.Relationships.Workspace.Data.Id = workspace.Result.Data.Id;
                var runsResult = await runsClient.Run.CreateAsync(runsRequest);
    
                // Get the Run Id. You'll need it to check teh state of the run and Apply it if possible.
                var runId = runsResult.Data.Id;
    
                var ready = false;
                while (!ready)
                {
                    // Wait for the Run to be planned .
                    await Task.Delay(5000);
                    var run = await client.Run.ShowAsync(runId);
                    ready = run.Data.Attributes.Status == "planned";
    
                    // Throw an exception if the Run status is: errored.
                    if (run.Data.Attributes.Status == "errored") {
                        throw new Exception("Plan failed...");
                    }
                }
    
                // If the Run is planned then Apply your configuration.
                if (ready)
                {
                    await runsClient.Run.ApplyAsync(runId, null);
                }
            }
        }
    }
    


    Tfe.NetClient is still in early stages of development and the resulting code is very verbose and prone to errors. We will address this in a future relases introducing the use of enums and perhaps a fluent API.



    5. 프로그램 실행




    다음 명령을 실행합니다.

    dotnet run
    


    6. 결과 확인




    Terraform Cloud에 로그인하여 새 작업 공간의 상태를 확인하십시오.

    도움이 되기를 바랍니다!

    좋은 웹페이지 즐겨찾기