com.amazonaws.services.cloudformation.model.Tag Java Examples

The following examples show how to use com.amazonaws.services.cloudformation.model.Tag. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TagTest.java    From herd-mdl with Apache License 2.0 6 votes vote down vote up
@Test
public void testSqsTagsAreSameAsHerdEC2Stack() throws Exception {
    String sqsNamePrefix = INSTANCE_NAME;
    String herdStackNamePrefix = APP_STACK_NAME + "-MdlStack-";

    CloudFormationClient cloudFormationClient = new CloudFormationClient(APP_STACK_NAME);
    List<Tag> stackTags = cloudFormationClient.getStackByNamePrefix(herdStackNamePrefix).getTags();

    System.out.println("Listing all queues with prefix: " + sqsNamePrefix);
    AmazonSQS sqs = AmazonSQSClientBuilder.standard().withRegion(Regions.getCurrentRegion().getName())
        .withCredentials(new InstanceProfileCredentialsProvider(true)).build();
    List<String> queueUrls = sqs.listQueues(sqsNamePrefix).getQueueUrls();
    assertEquals(2, queueUrls.size(), "2 queues are expected");
    for (String queueUrl : queueUrls) {
        System.out.println("QueueUrl: " + queueUrl);
        Map<String, String> sqsTags = sqs.listQueueTags(queueUrl).getTags();

        LogVerification("Verify sqs tags are the same as herd stack");
        stackTags.forEach(tag -> {
            String key = tag.getKey();
            assertTrue(sqsTags.containsKey(key));
            assertEquals(tag.getValue(), sqsTags.get(key));
        });
    }
}
 
Example #2
Source File: CFNUpdateStackSetStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createNonExistantStack() throws Exception {
	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithGlobalCredentials");
	Mockito.when(stackSet.exists()).thenReturn(false);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  cfnUpdateStackSet(stackSet: 'foo')"
			+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	PowerMockito.verifyNew(CloudFormationStackSet.class, Mockito.atLeastOnce())
			.withArguments(
					Mockito.any(AmazonCloudFormation.class),
					Mockito.eq("foo"),
					Mockito.any(TaskListener.class),
					Mockito.eq(SleepStrategy.EXPONENTIAL_BACKOFF_STRATEGY)
			);
	Mockito.verify(stackSet).create(Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class), Mockito.isNull(String.class), Mockito.isNull(String.class));
}
 
Example #3
Source File: CloudFormationStackSet.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
public CreateStackSetResult create(String templateBody, String templateUrl, Collection<Parameter> params, Collection<Tag> tags, String administratorRoleArn, String executionRoleName) {
	if ((templateBody == null || templateBody.isEmpty()) && (templateUrl == null || templateUrl.isEmpty())) {
		throw new IllegalArgumentException("Either a file or url for the template must be specified");
	}

	this.listener.getLogger().println("Creating stack set " + this.stackSet);
	CreateStackSetRequest req = new CreateStackSetRequest()
		.withStackSetName(this.stackSet)
		.withCapabilities(Capability.CAPABILITY_IAM, Capability.CAPABILITY_NAMED_IAM, Capability.CAPABILITY_AUTO_EXPAND)
		.withTemplateBody(templateBody)
		.withTemplateURL(templateUrl)
		.withParameters(params)
		.withAdministrationRoleARN(administratorRoleArn)
		.withExecutionRoleName(executionRoleName)
		.withTags(tags);
	CreateStackSetResult result = this.client.createStackSet(req);
	this.listener.getLogger().println("Created Stack set stackSetId=" + result.getStackSetId());
	return result;
}
 
Example #4
Source File: CFNUpdateStackSetStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createNonExistantStackWithCustomAdminArn() throws Exception {
	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithGlobalCredentials");
	Mockito.when(stackSet.exists()).thenReturn(false);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  cfnUpdateStackSet(stackSet: 'foo', administratorRoleArn: 'bar', executionRoleName: 'baz')"
			+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	PowerMockito.verifyNew(CloudFormationStackSet.class, Mockito.atLeastOnce())
			.withArguments(
					Mockito.any(AmazonCloudFormation.class),
					Mockito.eq("foo"),
					Mockito.any(TaskListener.class),
					Mockito.eq(SleepStrategy.EXPONENTIAL_BACKOFF_STRATEGY)
			);
	Mockito.verify(stackSet).create(Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class), Mockito.eq("bar"), Mockito.eq("baz"));
}
 
Example #5
Source File: CFNUpdateStackSetStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void doNotCreateNonExistantStack() throws Exception {
	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(stackSet.exists()).thenReturn(false);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  cfnUpdateStackSet(stackSet: 'foo', create: false)"
			+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	PowerMockito.verifyNew(CloudFormationStackSet.class, Mockito.atLeastOnce())
			.withArguments(
					Mockito.any(AmazonCloudFormation.class),
					Mockito.eq("foo"),
					Mockito.any(TaskListener.class),
					Mockito.eq(SleepStrategy.EXPONENTIAL_BACKOFF_STRATEGY)
			);
	Mockito.verify(stackSet, Mockito.never()).create(Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class), Mockito.isNull(String.class), Mockito.isNull(String.class));
}
 
Example #6
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createChangeSetStackParametersFromMap() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(true);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar', params: ['foo': 'bar', 'baz': 'true'])\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.anyString(), Mockito.anyString(), Mockito.eq(Arrays.asList(
			new Parameter().withParameterKey("foo").withParameterValue("bar"),
			new Parameter().withParameterKey("baz").withParameterValue("true")
	)), Mockito.anyCollectionOf(Tag.class), Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.UPDATE), Mockito.anyString(),
											   Mockito.any());
}
 
Example #7
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createChangeSetStackExists() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(true);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class),
											   Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.UPDATE), Mockito.anyString(), Mockito.any());
}
 
Example #8
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createChangeSetWithRawTemplate() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(true);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar', template: 'foobaz')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.eq("foobaz"), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class),
											   Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.UPDATE), Mockito.anyString(), Mockito.any());
}
 
Example #9
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void updateChangeSetWithRawTemplate() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(false);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar', template: 'foobaz')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.eq("foobaz"), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class),
											   Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.CREATE), Mockito.anyString(), Mockito.any());
}
 
Example #10
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createChangeSetStackDoesNotExist() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(false);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class),
											   Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.CREATE), Mockito.anyString(), Mockito.any());
}
 
Example #11
Source File: StackResourceUserTagsFactoryBeanTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void getObject_stackWithTagsDefined_createTagsMap() throws Exception {
	// Arrange
	AmazonCloudFormation cloudFormation = mock(AmazonCloudFormation.class);
	StackNameProvider stackNameProvider = mock(StackNameProvider.class);

	when(stackNameProvider.getStackName()).thenReturn("testStack");
	when(cloudFormation
			.describeStacks(new DescribeStacksRequest().withStackName("testStack")))
					.thenReturn(new DescribeStacksResult().withStacks(new Stack()
							.withTags(new Tag().withKey("key1").withValue("value1"),
									new Tag().withKey("key2").withValue("value2"))));

	StackResourceUserTagsFactoryBean factoryBean = new StackResourceUserTagsFactoryBean(
			cloudFormation, stackNameProvider);

	// Act
	factoryBean.afterPropertiesSet();
	Map<String, String> factoryBeanObject = factoryBean.getObject();

	// Assert
	assertThat(factoryBeanObject.get("key1")).isEqualTo("value1");
	assertThat(factoryBeanObject.get("key2")).isEqualTo("value2");
}
 
Example #12
Source File: CloudFormationStack.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
public Map<String, String> create(String templateBody, String templateUrl, Collection<Parameter> params, Collection<Tag> tags, Collection<String> notificationARNs, PollConfiguration pollConfiguration, String roleArn, String onFailure, Boolean enableTerminationProtection) throws ExecutionException {
	if ((templateBody == null || templateBody.isEmpty()) && (templateUrl == null || templateUrl.isEmpty())) {
		throw new IllegalArgumentException("Either a file or url for the template must be specified");
	}

	CreateStackRequest req = new CreateStackRequest();
	req.withStackName(this.stack).withCapabilities(Capability.CAPABILITY_IAM, Capability.CAPABILITY_NAMED_IAM, Capability.CAPABILITY_AUTO_EXPAND).withEnableTerminationProtection(enableTerminationProtection);
	req.withTemplateBody(templateBody).withTemplateURL(templateUrl).withParameters(params).withTags(tags).withNotificationARNs(notificationARNs)
			.withTimeoutInMinutes(pollConfiguration.getTimeout() == null ? null : (int) pollConfiguration.getTimeout().toMinutes())
			.withRoleARN(roleArn)
			.withOnFailure(OnFailure.valueOf(onFailure));
	this.client.createStack(req);

	new EventPrinter(this.client, this.listener).waitAndPrintStackEvents(this.stack, this.client.waiters().stackCreateComplete(), pollConfiguration);

	Map<String, String> outputs = this.describeOutputs();
	outputs.put(UPDATE_STATUS_OUTPUT, "true");
	return outputs;
}
 
Example #13
Source File: AwsStackRequestHelperTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCreateStackRequestForCloudStack() {
    when(cloudContext.getLocation()).thenReturn(Location.location(Region.region("region"), new AvailabilityZone("az")));
    DescribeImagesResult imagesResult = new DescribeImagesResult();
    when(amazonEC2Client.describeImages(any(DescribeImagesRequest.class)))
            .thenReturn(imagesResult.withImages(new com.amazonaws.services.ec2.model.Image()));
    when(network.getStringParameter(anyString())).thenReturn("");

    Collection<Tag> tags = Lists.newArrayList(new Tag().withKey("mytag").withValue("myvalue"));
    when(awsTaggingService.prepareCloudformationTags(authenticatedContext, cloudStack.getTags())).thenReturn(tags);

    CreateStackRequest createStackRequest =
            underTest.createCreateStackRequest(authenticatedContext, cloudStack, "stackName", "subnet", "template");

    assertEquals("stackName", createStackRequest.getStackName());
    assertEquals("template", createStackRequest.getTemplateBody());

    verify(awsTaggingService).prepareCloudformationTags(authenticatedContext, cloudStack.getTags());
    assertEquals(tags, createStackRequest.getTags());
}
 
Example #14
Source File: AWSProvider.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 *
 * Logs are retrieved via aws api that looks similar to this cli command:
 * aws ec2 get-console-output --instance-id i-123456789abcd --output text
 *
 * This won't contain the entire ec2 instance console (system) log.
 * It'll be truncated to last {@link #EC2_SYSTEM_LOG_NO_OF_LINES} lines.
 *
 * @param instance the ec2 instance object
 * @param amazonEC2 AmazonEC2 command handler
 * @return return string will be of following format:
 * <pre>
 *  ${ec2-nickname} logs {
 *      <br/>
 *      ${truncated-logs}
 *      <br/>
 *  }
 * </pre>
 */
private String getEC2InstanceConsoleLogs(Instance instance, AmazonEC2 amazonEC2) {
    String decodedOutput;
    String instanceName = instance.getTags().stream()
            .filter(t -> t.getKey().equals("Name"))
            .map(com.amazonaws.services.ec2.model.Tag::getValue)
            .findAny().orElse("<name-empty>");
    try {
        GetConsoleOutputRequest consoleOutputRequest = new GetConsoleOutputRequest(instance.getInstanceId());
        final GetConsoleOutputResult consoleOutputResult = amazonEC2.getConsoleOutput(consoleOutputRequest);
        decodedOutput = consoleOutputResult.getDecodedOutput();
        decodedOutput = reduceLogVerbosity(decodedOutput);

    } catch (NullPointerException e) {
        String error = e.getMessage() +
                (e.getStackTrace().length > 0 ? "at " + e.getStackTrace()[0].toString() : "");
        decodedOutput = "Error occurred while retrieving instance console logs for " + instance.getInstanceId() +
                ". Error: " + error;
    }

    return instanceName + " logs {\n" +
            decodedOutput + "\n" +
            "}\n";
}
 
Example #15
Source File: AWSProvider.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a ssh login command for *nix to access the given ec2 instance.
 *
 * @param instance the ec2 instance
 * @return ssh login command.
 */
private String getLoginCommand(Instance instance) {
    final String privateIpAddress = instance.getPrivateIpAddress();
    String publicAddress = instance.getPublicDnsName();
    publicAddress = publicAddress == null ? instance.getPublicIpAddress() : publicAddress;
    final String keyName = instance.getKeyName();
    String instanceName = instance.getTags().stream()
            .filter(t -> t.getKey().equals("Name"))
            .map(com.amazonaws.services.ec2.model.Tag::getValue)
            .findAny().orElse("");
    instanceName = instanceName.isEmpty() ? "" : "# name: " + instanceName;
    String platform = instance.getPlatform();
    platform = platform == null || platform.isEmpty() ? "" : "# platform: " + platform;

    String ip;
    if (publicAddress != null && !publicAddress.isEmpty()) {
        ip = publicAddress;
    } else {
        ip = privateIpAddress;
    }

    //root user is assumed. EC2 instances print the actual user name when tried to log-in as the root user.
    return "ssh -i " + keyName + " root@" + ip + ";   " + instanceName + platform;
}
 
Example #16
Source File: StackResourceUserTagsFactoryBean.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, String> createInstance() throws Exception {
	LinkedHashMap<String, String> userTags = new LinkedHashMap<>();
	DescribeStacksResult stacksResult = this.amazonCloudFormation
			.describeStacks(new DescribeStacksRequest()
					.withStackName(this.stackNameProvider.getStackName()));
	for (Stack stack : stacksResult.getStacks()) {
		for (Tag tag : stack.getTags()) {
			userTags.put(tag.getKey(), tag.getValue());
		}
	}
	return userTags;
}
 
Example #17
Source File: TestStackEnvironment.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private DescribeStackResourcesResult getStackResources(String stackName)
		throws InterruptedException, IOException {
	try {
		DescribeStacksResult describeStacksResult = this.amazonCloudFormationClient
				.describeStacks(new DescribeStacksRequest().withStackName(stackName));
		for (Stack stack : describeStacksResult.getStacks()) {
			if (isAvailable(stack)) {
				return this.amazonCloudFormationClient
						.describeStackResources(new DescribeStackResourcesRequest()
								.withStackName(stack.getStackName()));
			}
			if (isError(stack)) {
				if (this.stackCreatedByThisInstance) {
					throw new IllegalArgumentException("Could not create stack");
				}
				this.amazonCloudFormationClient.deleteStack(
						new DeleteStackRequest().withStackName(stack.getStackName()));
				return getStackResources(stackName);
			}
			if (isInProgress(stack)) {
				// noinspection BusyWait
				Thread.sleep(5000L);
				return getStackResources(stackName);
			}
		}
	}
	catch (AmazonClientException e) {
		String templateBody = FileCopyUtils.copyToString(new InputStreamReader(
				new ClassPathResource(TEMPLATE_PATH).getInputStream()));
		this.amazonCloudFormationClient.createStack(new CreateStackRequest()
				.withTemplateBody(templateBody).withOnFailure(OnFailure.DELETE)
				.withStackName(stackName)
				.withTags(new Tag().withKey("tag1").withValue("value1"))
				.withParameters(new Parameter().withParameterKey("RdsPassword")
						.withParameterValue(this.rdsPassword)));
		this.stackCreatedByThisInstance = true;
	}

	return getStackResources(stackName);
}
 
Example #18
Source File: AwsNetworkConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private CreateStackRequest createStackRequest(String stackName, String cloudFormationTemplate, Map<String, String> tags, String creatorUser) {
    Collection<Tag> awsTags = awsTaggingService.prepareCloudformationTags(null, tags);
    return new CreateStackRequest()
            .withStackName(stackName)
            .withOnFailure(OnFailure.DO_NOTHING)
            .withTemplateBody(cloudFormationTemplate)
            .withTags(awsTags)
            .withCapabilities(CAPABILITY_IAM);
}
 
Example #19
Source File: AwsStackRequestHelperTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateCreateStackRequestForDatabaseStack() {
    Collection<Tag> tags = Lists.newArrayList(new Tag().withKey("mytag").withValue("myvalue"));
    when(awsTaggingService.prepareCloudformationTags(authenticatedContext, databaseStack.getTags())).thenReturn(tags);

    CreateStackRequest createStackRequest =
            underTest.createCreateStackRequest(authenticatedContext, databaseStack, "stackName", "template");

    assertEquals("stackName", createStackRequest.getStackName());
    assertEquals("template", createStackRequest.getTemplateBody());

    verify(awsTaggingService).prepareCloudformationTags(authenticatedContext, cloudStack.getTags());
    assertEquals(tags, createStackRequest.getTags());
}
 
Example #20
Source File: AwsTaggingServiceTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testWhenUserTagsDefined() {
    Map<String, String> userDefined = Maps.newHashMap();
    userDefined.put("userdefinedkey", "userdefinedvalue");
    Collection<Tag> tags = awsTaggingService.prepareCloudformationTags(authenticatedContext(), userDefined);
    assertEquals(1L, tags.size());
}
 
Example #21
Source File: TagsReader.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
public static List<Tag> getStackTags() {
    List<Map<String, String>> tagsList = CsvFileReader.readCSVFile("tags.csv");
    return tagsList.stream().map(x -> {
        Tag tag = new Tag();
        tag.setKey(x.get(TAG_KEY));
        tag.setValue(x.get(TAG_VALUE));
        return tag;
    }).collect(Collectors.toList());
}
 
Example #22
Source File: AwsTaggingServiceTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void tesTagRootVolumesForSingleInstance() {
    CloudResource instance = CloudResource.builder()
            .type(ResourceType.AWS_INSTANCE).instanceId(INSTANCE_ID).name(INSTANCE_ID).status(CommonStatus.CREATED).build();

    DescribeInstancesResult describeResult = new DescribeInstancesResult()
            .withReservations(new Reservation()
                    .withInstances(new Instance()
                            .withInstanceId(INSTANCE_ID)
                            .withBlockDeviceMappings(new InstanceBlockDeviceMapping()
                                    .withDeviceName("/dev/sda1")
                                    .withEbs(new EbsInstanceBlockDevice().withVolumeId(VOLUME_ID)))
                            .withRootDeviceName("/dev/sda1"))
            );

    AmazonEC2Client ec2Client = mock(AmazonEC2Client.class);
    when(ec2Client.describeInstances(any())).thenReturn(describeResult);
    Map<String, String> userTags = Map.of("key1", "val1", "key2", "val2");

    awsTaggingService.tagRootVolumes(authenticatedContext(), ec2Client, List.of(instance), userTags);

    verify(ec2Client, times(1)).createTags(tagRequestCaptor.capture());
    CreateTagsRequest request = tagRequestCaptor.getValue();
    assertEquals(1, request.getResources().size());
    assertEquals(VOLUME_ID, request.getResources().get(0));
    List<com.amazonaws.services.ec2.model.Tag> tags = request.getTags();
    assertThat(tags, containsInAnyOrder(
            hasProperty("key", Matchers.is("key1")),
            hasProperty("key", Matchers.is("key2"))
    ));
    assertThat(tags, containsInAnyOrder(
            hasProperty("value", Matchers.is("val1")),
            hasProperty("value", Matchers.is("val2"))
    ));
}
 
Example #23
Source File: CFNUpdateStackTests.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void doNotCreateNonExistantStack() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(false);
	Mockito.when(this.stack.describeOutputs()).thenReturn(Collections.singletonMap("foo", "bar"));
	job.setDefinition(new CpsFlowDefinition(""
													+ "node {\n"
													+ "  cfnUpdate(stack: 'foo', create: false)"
													+ "}\n", true)
	);
	this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	Mockito.verify(this.stack, Mockito.never()).create(Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class), Mockito.anyCollectionOf(String.class), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean());
}
 
Example #24
Source File: CFNUpdateStackTests.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void createNonExistantStack() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithGlobalCredentials");
	Mockito.when(this.stack.exists()).thenReturn(false);
	Mockito.when(this.stack.describeOutputs()).thenReturn(Collections.singletonMap("foo", "bar"));
	job.setDefinition(new CpsFlowDefinition(""
													+ "node {\n"
													+ "  cfnUpdate(stack: 'foo')"
													+ "}\n", true)
	);
	this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	Mockito.verify(this.stack).create(Mockito.anyString(), Mockito.anyString(), Mockito.<Parameter>anyCollection(), Mockito.<Tag>anyCollection(), Mockito.<String>anyCollection(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean());
}
 
Example #25
Source File: TagTest.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
private List<com.amazonaws.services.ec2.model.Tag> getSecurityGroupTagsWithPrefix(String sgNamePrefix) {
    assertNotNull(sgNamePrefix);

    AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard().withRegion(Regions.getCurrentRegion().getName())
        .withCredentials(new InstanceProfileCredentialsProvider(true)).build();
    List<SecurityGroup> securityGroups = ec2.describeSecurityGroups().getSecurityGroups().stream()
        //exclude security group created by DeployHostStack, as DeployHostStack doesn't have tag attached
        .filter(sg -> sg.getGroupName().startsWith(sgNamePrefix) && !sg.getGroupName().trim().endsWith(DEPLOY_HOST_SG_SUFFIX))
        .collect(Collectors.toList());
    assert securityGroups != null && securityGroups.size() > 0;

    LOGGER.info("Getting SG: " + securityGroups.get(0).getGroupName());
    return securityGroups.get(0).getTags();
}
 
Example #26
Source File: TagTest.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
private List<com.amazonaws.services.elasticloadbalancingv2.model.Tag> getElbTags() {
    String elbArn = getAnyElbArn();

    AmazonElasticLoadBalancing client = AmazonElasticLoadBalancingClientBuilder.standard()
        .withRegion(Regions.getCurrentRegion().getName()).withCredentials(new InstanceProfileCredentialsProvider(true))
        .build();
    DescribeTagsRequest request = new DescribeTagsRequest().withResourceArns(elbArn);
    return client.describeTags(request).getTagDescriptions().get(0).getTags();
}
 
Example #27
Source File: CFNCreateChangeSetStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public List<Change> whenStackExists(Collection<Parameter> parameters, Collection<Tag> tags, Collection<String> notificationARNs, RollbackConfiguration rollbackConfiguration) throws Exception {
	final String changeSet = this.getStep().getChangeSet();
	final String url = this.getStep().getUrl();
	this.getCfnStack().createChangeSet(changeSet, this.getStep().readTemplate(this), url, parameters, tags, notificationARNs, this.getStep().getPollConfiguration(), ChangeSetType.UPDATE, this.getStep().getRoleArn(), rollbackConfiguration);
	return this.validateChangeSet(changeSet);
}
 
Example #28
Source File: CFNCreateChangeSetStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public List<Change> whenStackMissing(Collection<Parameter> parameters, Collection<Tag> tags, Collection<String> notificationARNs) throws Exception {
	final String changeSet = this.getStep().getChangeSet();
	final String url = this.getStep().getUrl();
	this.getCfnStack().createChangeSet(changeSet, this.getStep().readTemplate(this), url, parameters, tags, notificationARNs, this.getStep().getPollConfiguration(), ChangeSetType.CREATE, this.getStep().getRoleArn(), null);
	return this.validateChangeSet(changeSet);
}
 
Example #29
Source File: TagsFileParser.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
public static Collection<Tag> parseTags(InputStream is) throws IOException {
	ObjectMapper mapper = new ObjectMapper();
	JsonNode tree = mapper.readTree(is);
	ArrayNode jsonNodes = (ArrayNode) tree;
	return StreamSupport.stream(jsonNodes.spliterator(), false)
			.map(node -> {
				return new Tag()
						.withKey(node.get("Key").asText())
						.withValue(node.get("Value").asText());
			})
			.collect(Collectors.toList());
}
 
Example #30
Source File: CloudFormationStack.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
public void createChangeSet(String changeSetName, String templateBody, String templateUrl, Collection<Parameter> params, Collection<Tag> tags, Collection<String> notificationARNs, PollConfiguration pollConfiguration, ChangeSetType changeSetType, String roleArn, RollbackConfiguration rollbackConfig) throws ExecutionException {
	ChangeSetType effectiveChangeSetType;
	if (isInReview()) {
		effectiveChangeSetType = ChangeSetType.CREATE;
	} else {
		effectiveChangeSetType = changeSetType;
	}
	doCreateChangeSet(changeSetName, templateBody, templateUrl, params, tags, notificationARNs, pollConfiguration, effectiveChangeSetType, roleArn, rollbackConfig);
}